<template>
  <div class="xtx-pagination">
    <a
      href="javascript:;"
      :class="{ disabled: currPage === 1 }"
      @click="pageClick(-1)"
      >上一页</a
    >
    <span v-if="pager[0] > 1">...</span>
    <a
      href="javascript:;"
      :class="{ active: currPage === item }"
      v-for="item in pager"
      :key="item"
      >{{ item }}</a
    >
    <span v-if="pager[pager.length - 1] < totalPage">...</span>
    <a
      href="javascript:;"
      :class="{ disabled: currPage >= totalPage }"
      @click="pageClick(1)"
      >下一页</a
    >
  </div>
</template>
<script>
import { watch, reactive, toRefs } from 'vue'
export default {
  name: 'XtxPagination',
  props: {
    page: {
      type: Number,
      default: 1
    },
    pagesize: {
      type: Number,
      default: 10
    },
    total: {
      type: Number,
      default: 100
    }
  },
  setup (props, { emit }) {
    const pageStep = 5 // 页码最多显示五条
    //   1:定义相应的变量用于分页组件
    const pagination = reactive({
      currPage: 1, // 当前页码
      totalPage: 10, // 总页码
      initPager: [], // 所有页码的数组
      pager: [1, 2, 3, 4, 5] // 通过计算出来的需要展示的页码
    })
    watch(
      props,
      () => {
        pagination.currPage = props.page
        pagination.totalPage = Math.ceil(props.total / props.pagesize)
        for (let i = 1; i <= pagination.totalPage; i++) {
          pagination.initPager[i - 1] = i
        }
        setPager()
      },
      {
        immediate: true
      }
    )
    // 页码一变化 就再一次计算
    watch(
      () => pagination.currPage,
      () => {
        setPager()
        emit('pageChange', pagination.currPage)
      }
    )
    // 页码点击事件，上一页与下一页功能
    function pageClick (step) {
      const _temp = pagination.currPage + step
      if (_temp > 0 && _temp <= pagination.totalPage) {
        pagination.currPage = _temp
      }
    }
    function setPager () {
      let min = pagination.currPage - 3 // 最小值
      let max = 5 + min // 最大值
      // max-min=5
      if (min < 0) {
        min = 0
        max = 5 + min
      }
      //   如果max超过最大值
      if (max > pagination.totalPage) {
        max = pagination.totalPage
        min = max - 5 >= 0 ? max - 5 : 0
      }
      pagination.pager = pagination.initPager.slice(min, max) // 0    5
    }

    return { pageClick, ...toRefs(pagination) }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333;
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
